<template>
    <div class="container">
        <el-dialog v-model="props.listDialogVisible" title="批量上传" width="60%" :before-close="close"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <div style="padding-bottom: 10px;">
                <el-steps :active="active" finish-status="success">
                    <el-step title="上传文件" />
                    <el-step title="上传讲义" />
                </el-steps>
            </div>
            <div v-if="step">
                <el-form ref="formRef" :model="validateForm"  class="demo-ruleForm">
                        <el-form-item label="课程标签" prop="age">
                            <el-input v-model.number="validateForm.identity" type="text" autocomplete="off" style="width: 200px;" />
                        </el-form-item>
                </el-form>
                <el-upload class="upload-demo" drag action="#" multiple :http-request="uploadVideo" :on-change="changeVideo"
                    :before-upload="beforeUpload" :on-remove="removeFile" :indeterminate="true" :duration="5">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        批量拖拽文件到这上传或<em>选择文件</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            请上传视频文件，格式为MP4,视频文件不超过1GB
                        </div>
                    </template>
                </el-upload>
                <el-progress v-if="showJinDuTao" style="width: 200px; margin-top: 8px" :percentage="progressPercent" />
            </div>
            <div class="table-data" v-else>
                <div>
                    <el-button type="danger" :icon="CloseBold" @click="deleteAll">批量删除</el-button>
                </div>
                <div>
                    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="class_name" label="课时名称" />
                        <el-table-column label="课时时长">
                            <template #default="scope">
                                {{ getHour(scope.row.class_time) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="选择讲师">
                            <template #default="scope">
                                <el-select v-model="scope.row.cphonlass_name_e" placeholder="请选择讲师" @change="changeValue">
                                    <el-option v-for="item, index in scope.row.options" :key="index"
                                        :label="item.name + '-' + item.phone" :value="item.name + '@?-+' + item.phone + '@?-+' + scope.row.class_time + '@?-+' + scope.row.class_number + '@?-+' + item.picture[0].url + '@?-+' +
                                            scope.row.class_name" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="上传讲义">
                            <template #default="scope">
                                <div style="display: flex;align-items: center;">
                                    <el-upload ref="uploadRef" class="upload-demo" action="#"
                                        :before-upload="beforeUploadPdf(scope.row.class_number)" :http-request="(file) => {
                                            return uploadRquest(file, scope.row);
                                        }" :show-file-list="false">
                                        <template #trigger>
                                            <el-button type="primary" :loading="scope.row.loading" size="small"
                                                :disabled="scope.row.disabled"
                                                v-if="!scope.row.showProgress">上传讲义</el-button>
                                            <div v-if="scope.row.showProgress">
                                                <div>{{ scope.row.fileName }}</div>
                                                <el-progress style="width: 100px;"
                                                    :percentage="scope.row.progressPercent" />
                                            </div>
                                        </template>
                                    </el-upload>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <div style="margin-right: 10px;">
                                    <el-button type="danger" :icon="CloseBold" @click="deleteOne(scope.row.class_number)"
                                        size="small">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitVideo" v-if="step" :loading="loadingIcon">
                        点击上传
                    </el-button>
                    <el-button type="primary" @click="lastStep" v-if="!step">
                        上一步
                    </el-button>
                    <el-button type="primary" v-if="!step" @click="closeDiglog">
                        完成
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>  
</template>

<script setup lang="ts">
import { UploadFile, UploadFiles, UploadProgressEvent, UploadRawFile, UploadRequestOptions } from 'element-plus';
import { uploadFileList, deleteCourse, deleteCourseList } from '../api/uploadVideoList'
import { sumbitLesson, uploadFdf, searchTeacher } from '../api/uploadVideo'
import { CloseBold, Plus ,UploadFilled} from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import request from "../utils/http/request";
import { getHour } from '../utils/date';
import { ElMessage } from 'element-plus'
const props = defineProps(['listDialogVisible'])
const emits = defineEmits(['closeDiglog'])
const closeDiglog = () => {
    //关闭对话框前判断是否绑定老师
    let _show = tableData.value.every((item: any) => item.class_name_phone)
    if (!_show && active.value === 2) {
        return ElMessage.error('请选择讲师')
    }
    lastStep() //上一步
    emits('closeDiglog')
}
//关闭对话框
const close = () => {
    //关闭对话框前判断是否绑定老师
    let _show = tableData.value.every((item: any) => item.class_name_phone)
    if (!_show && active.value === 2) {
        return ElMessage.error('请选择讲师')
    }
    if (active.value === 1) {
        files = []
        lessonForms = []
        class_time.value = []
    }
    emits('closeDiglog')
}
const uploadVideo = (options: UploadRequestOptions) => {
    // console.log(options)
}

const changeVideo = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    // console.log(uploadFile,'多个文件')
}
//下拉选项值
const changeValue = (e: any) => {
    console.log(e)
    let [name, phone, class_time, class_number, picture, class_name] = e.split('@?-+')
    let params = {
        class_number,
        class_teacher: name,
        class_time,
        teacher_phone: phone,
        picture,
        class_name
    }
    sumbitLesson(params).then((res: any) => {
        if (res) {
            console.log('修改成功')
        }
    })
}
let files: any = [] //选择的文件列表
let lessonForms: any = [] //文件名称数组
const class_time: any = ref({}) //文件时间列表
const beforeUpload = (rawFile: UploadRawFile) => {
    files.push(rawFile)
    var url = URL.createObjectURL(rawFile);
    var audioElement = new Audio(url);
    var duration;
    audioElement.addEventListener("loadedmetadata", function (_event) {
        duration = parseInt(audioElement.duration.toString());
        class_time.value[rawFile.name.split('.mp4')[0]] = duration
    });
}
//显示进度条
const showJinDuTao = ref(false)
const progressPercent = ref(0)
//上传文件
const active = ref(1)
const step = ref(true)
const tableData: any = ref([])
const loadingIcon = ref(false)
const submitVideo = () => {
    if (loadingIcon.value) {
        ElMessage.error('等待视频上传完成')
        return
    }
    if (files.length === 0) {
        ElMessage.error('请选择文件')
        return
    }
    if(validateForm.identity.length===0){
        return ElMessage.error('请填写课程标识')
    }
    let data: any = localStorage.getItem('token')
    let { teacher_name, phone } = JSON.parse(data)
    let form:any = new FormData()

    const find = files.every(file => file.type == 'video/mp4' || file.type == 'video/quicktime')
    if (!find) {
        ElMessage.error('请选择文件格式为mp4、mov')
        return
    }
    files.forEach((file: any) => {
        if (file.type === 'video/mp4') {
            lessonForms.push(file.name.split('.mp4')[0])
        } else {
            lessonForms.push(file.name.split('.mov')[0])
        }
        form.append('video', file)
    })
    form.append('updateUserName', teacher_name)
    form.append('updateUsserPhone', phone)
    form.append("class_names", lessonForms.join(','))
    form.append('identity',validateForm.identity)
    // form.append('size',(files.size)/(1024*1024))
    loadingIcon.value = true
    showJinDuTao.value = true
    request({
        url: "/lesson/batchInsert",
        method: "post",
        data: form,
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        timeout: 100000000,
        onUploadProgress: (progressEvent: any) => {
            progressPercent.value = Number(
                ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
            )
            //   上传进度和对勾显示时间不相符,让进度条卡到98,等后台返回结果在显示100
            if (progressPercent.value >= 98) {
                progressPercent.value = 98
            }
        }
    }).then(res => {
        lessonForms = []
        files = []
        if (res.code === '200') {
            progressPercent.value = 100
            showJinDuTao.value = false
            ElMessage.success(res.msg)
            loadingIcon.value = false
            tableData.value = res.data
            step.value = false
            tableData.value.forEach((key) => {
                key.options = JSON.parse(JSON.stringify(options))
                key.class_name_phone = ''
                key.loading = false
                key.disabled = false
                key.showProgress = false
                key.progressPercent = 0
                key.fileName = ''
                for (let time in class_time.value) {
                    if (time === key.class_name) {
                        key.class_time = class_time.value[time]
                    }
                }
            })
            step.value = false
            active.value = 2
        } else {
            loadingIcon.value = false
            ElMessage.error('上传失败')
        }
    }).catch(error=>{
        ElMessage.error('上传失败')
        showJinDuTao.value = false
        loadingIcon.value = false
    })
}
const removeFile = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    const findIndex = files.findIndex((item: any) => item.uid === uploadFile.uid)
    files.splice(findIndex, 1)
}
//上一步
const lastStep = () => {
    step.value = true
    active.value = 1
}
let options: any = []

const getTeacherList = () => {
    searchTeacher({ name: '', phone: '' }).then(res => {
        if (res) {
            options = res?.list || []
        }
    })
}
getTeacherList()
//删除课时(单个)
const deleteOne = (id: string) => {
    let data: any = localStorage.getItem('token')
    let { teacher_name, phone } = JSON.parse(data)
    let params = {
        class_number: id,
        updateUserName: teacher_name,
        updateUsserPhone: phone
    }

    deleteCourse(params).then(res => {
        if (res.code === '200') {
            let index = tableData.value.findIndex(item => item.class_number === id)
            tableData.value.splice(index, 1)
            ElMessage.success('删除成功')
        }
    })
}
//多选
const idList = ref([])
const handleSelectionChange = (val: any) => {
    idList.value = val
}
//批量删除
const deleteAll = () => {
    if (idList.value.length === 0) {
        ElMessage.error('请选择课时')
        return
    }
    let data: any = localStorage.getItem('token')
    let { teacher_name, phone } = JSON.parse(data)
    let params = {
        ids: idList.value.map(item => item.class_number).join(','),
        updateUserName: teacher_name,
        updateUsserPhone: phone
    }
    console.log(params)
    deleteCourseList(params).then(res => {
        if (res.code === '200') {
            tableData.value = tableData.value.filter(item => {
                for (let key of idList.value) {
                    if (item.class_number !== key) {
                        return true
                    }
                }
            })
            ElMessage.success('删除成功')
        }
    })
}

//上传讲义
const beforeUploadPdf = (file: any) => { }

//手动上传
const uploadRquest = (file: any, item: any) => {
    let form = new FormData()
    form.append('file', file.file)
    form.append('class_number', item.class_number)
    request({
        url: "/lesson/uploadFile",
        method: "post",
        data: form,
        onUploadProgress: (progressEvent: any) => {
            item.progressPercent = Number(
                ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
            )
            //   上传进度和对勾显示时间不相符,让进度条卡到98,等后台返回结果在显示100
            if (item.progressPercent.value >= 98) {
                item.progressPercent.value = 98
            }
        }
    }).then(res => {
        item.loading = false
        item.disabled = true
    })
}

//添加分类标识功能
const validateForm = reactive({
    identity: '',
})
</script>

<style scoped></style>